<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">销售日志</h1>
    </div>
    
    <!-- 搜索栏 -->
    <n-card style="margin-bottom: 16px;">
      <n-space>
        <n-input 
          v-model:value="searchParams.orderNo" 
          placeholder="搜索订单号" 
          clearable 
          style="width: 200px;"
        />
        <n-date-picker 
          v-model:value="searchParams.dateRange" 
          type="datetimerange" 
          clearable 
          placeholder="选择时间范围"
          style="width: 360px;"
        />
        <n-button type="primary" @click="handleSearch">搜索</n-button>
        <n-button @click="handleReset">重置</n-button>
      </n-space>
    </n-card>
    
    <!-- 表格 -->
    <div class="table-wrapper">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        @update:page="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, h, onMounted, reactive } from 'vue'
import { getSalesLogPage } from '@/api/sales'
import { NCard, NSpace, NInput, NDatePicker, NButton, NDataTable, NTag, useMessage } from 'naive-ui'

const message = useMessage()

const loading = ref(false)
const tableData = ref([])

const searchParams = reactive({
  orderNo: '',
  dateRange: null
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

const columns = [
  { title: '订单号', key: 'orderNo', width: 180 },
  { 
    title: '操作类型', 
    key: 'operationType',
    render: (row) => {
      const type = row.operationType === '新增销售' ? 'success' : 'warning'
      return h(NTag, { type }, { default: () => row.operationType })
    }
  },
  { title: '操作时间', key: 'operationTime', width: 180 },
  { title: '操作详情', key: 'operationDetail', ellipsis: { tooltip: true } }
]

async function loadData() {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.pageSize,
      orderNo: searchParams.orderNo || undefined
    }
    
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.startTime = new Date(searchParams.dateRange[0]).toISOString().slice(0, 19).replace('T', ' ')
      params.endTime = new Date(searchParams.dateRange[1]).toISOString().slice(0, 19).replace('T', ' ')
    }
    
    const res = await getSalesLogPage(params)
    tableData.value = res.data.records
    pagination.itemCount = res.data.total
  } catch (error) {
    message.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  pagination.page = 1
  loadData()
}

function handleReset() {
  searchParams.orderNo = ''
  searchParams.dateRange = null
  pagination.page = 1
  loadData()
}

function handlePageChange(page) {
  pagination.page = page
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

